<template>
     <div ref="pieChart" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import {ref,reactive,onMounted, onUnmounted,getCurrentInstance,watch} from 'vue'
const { proxy } = getCurrentInstance();
const echarts = proxy.$echarts;
const pieChart = ref(null); // 容器 DOM 引用
let chartInstance = null;   // ECharts 实例
const props = defineProps({
  data: Array,
});
watch(()=>props.data,()=>{
  if (!chartInstance && pieChart.value) {
    chartInstance = echarts.init(pieChart.value);
    window.addEventListener('resize', handleResize);
  }
  chartInstance?.setOption(options.value);
},{deep:true})
const options = computed(()=>(
  {
  title: {
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    backgroundColor:'rgba(23,47,73,0.8)',
    borderColor:'#41ACFF',
    textStyle:{
              color: "#FFFFFF"
    },
    formatter: params => {
      const total = props.data.reduce((sum, item) => sum + item.value, 0);
      const percent = ((params.value / total) * 100).toFixed(2);
      return `${params.name}<br/>
              数值: ${params.value}<br/>
              占比: ${percent}%`;
    }
  },
  legend: {
    left: 'center',
    top: 'bottom',
    data: [
      'rose1',
      'rose2',
      'rose3',
      'rose4',
    ]
  },
  toolbox: {
    show: false,
    feature: {
      mark: { show: true },
      dataView: { show: true, readOnly: false },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  series: [
    {
    //   name: 'Area Mode',
        label:{
            textStyle: {
              color: "#fff",
              fontSize: 14,
            },
            show:true,
        },
      type: 'pie',
      radius: [7, 50],
      center: ['45%', '45%'],
      roseType: 'area',
      data:props.data?.filter(item => item.count > 0)
    }
  ]
}
))

const handleResize = () => {
  chartInstance.resize()
};

onMounted(() => {
  nextTick(()=>{
    if (pieChart.value && !chartInstance) {
      chartInstance = echarts.init(pieChart.value);
      chartInstance.setOption(options.value);
      window.addEventListener('resize', handleResize);
    }
  })
});
onUnmounted(() => {
     window.removeEventListener('resize', handleResize);
     chartInstance.dispose();
   });
</script>

<style lang="scss" scoped>

</style>